// CreateLog.cpp: implementation of the CCreateLog class.
//
//////////////////////////////////////////////////////////////////////

#include "stdafx.h"
#include "iTrans.h"
#include "CreateLog.h"

#ifdef _DEBUG
#define new DEBUG_NEW
#endif

//////////////////////////////////////////////////////////////////////
// Construction/Destruction
//////////////////////////////////////////////////////////////////////

CCreateLog::CCreateLog() {}

CCreateLog::~CCreateLog() {}

void CCreateLog::CreateLog(LPCTSTR lpFilename)
{
	csFilename = lpFilename;
	FILE *f;
	if (_tfopen_s(&f, lpFilename, _T("wb")) || !f) return;

	static BYTE bBOM[] = {0xff, 0xfe};
	fwrite(bBOM, 1, 2, f);
	fclose(f);
}

void CCreateLog::WriteLog(LPCTSTR lpStr, LPCTSTR lpStr2, bool bWriteTime)
{
	static BYTE bBOM[] = {0x0d, 0x00, 0x0a, 0x00};

	if (csFilename.IsEmpty() || (!lpStr)) return;
	FILE *f;
	if (_tfopen_s(&f, csFilename, _T("r+b")) || !f) return;
	fseek(f, 0, SEEK_END);

	if (bWriteTime) {
		SYSTEMTIME stime;
		GetLocalTime(&stime);
		
		CString cs;
		cs.Format(_T("* [%04d.%02d.%02d %02d:%02d:%02d.%03d] "), stime.wYear, stime.wMonth, stime.wDay, stime.wHour, stime.wMinute, stime.wSecond, stime.wMilliseconds);
		
		fwrite(static_cast<LPCTSTR>(cs), sizeof(TCHAR), cs.GetLength(), f);
	} else if ((lpStr[0]==_TCHAR('#')) && (lpStr[1]==_TCHAR(' '))) {
		fwrite(bBOM, 1, 4, f);
	}

	fwrite(lpStr, sizeof(TCHAR), _tcslen(lpStr), f);
	if (lpStr2) fwrite(lpStr2, sizeof(TCHAR), _tcslen(lpStr2), f);

	fwrite(bBOM, 1, 4, f);

	fclose(f);
}


#define BUFSIZE 256

void CCreateLog::WriteSystemInfo(LPCTSTR lpOsInfoStr, LPCTSTR lpMemInfoStr, CString &csVersion)
{
	TCHAR tcBuf[BUFSIZE];
	LPCTSTR tcAppName = _T("iTrans von TEUS.me");

	_stprintf_s(tcBuf, BUFSIZE, _T("_%s v%s job log_"), tcAppName, static_cast<LPCTSTR>(csVersion));
	WriteLog(tcBuf, NULL, false);

	WriteLog(_T("# default infos"), NULL, false);

	CString csTeusMeAddr;
	csTeusMeAddr.LoadString(IDS_TEUSMEADDR);
	_stprintf_s(tcBuf, BUFSIZE, _T("Job log of iTrans: **%s v%s** [iTrans](%s)"), tcAppName, static_cast<LPCTSTR>(csVersion), static_cast<LPCTSTR>(csTeusMeAddr));
	WriteLog(tcBuf);

	WriteLog(lpOsInfoStr);
	WriteLog(lpMemInfoStr);
}

